package com.sj.uabrowser.framework;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.classic.common.MultipleStatusView;
import com.sj.uabrowser.BuildConfig;
import com.sj.uabrowser.R;
import com.sj.uabrowser.app.Constant;
import com.sj.uabrowser.app.SHASecrete;
import com.sj.uabrowser.app.SPUtil;
import com.sj.uabrowser.app.StatusBarUtil;
import com.sj.uabrowser.app.TApp;
import com.sj.uabrowser.app.Util;
import com.sj.uabrowser.db.gen.DaoSession;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
//import com.umeng.message.PushAgent;

import java.util.Date;
import java.util.TreeMap;

import butterknife.ButterKnife;

public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements BaseView<P> {

    public static final String TAG = BaseActivity.class.getSimpleName();
    public static final int MODE_DEFAULT = 0;

    public static final int MODE_SONIC = 1;

    public static final int MODE_SONIC_WITH_OFFLINE_CACHE = 2;

    private static final int PERMISSION_REQUEST_CODE_STORAGE = 1;
    protected P presenter;
    ProgressDialog progressDialog;
    protected PopupWindow popupWindowShared;

    protected View.OnClickListener shareListener;
    private View popShare;

    public DaoSession daoSession;
    public boolean noTrace;

    public void setShareListener(View.OnClickListener shareListener) {
        this.shareListener = shareListener;
        if (popShare != null) {
            RelativeLayout rlWechat = popShare.findViewById(R.id.rl_wechat);
            RelativeLayout rlFriends = popShare.findViewById(R.id.rl_friends);
            RelativeLayout rlQQ = popShare.findViewById(R.id.rl_qq);
            RelativeLayout rlQQZone = popShare.findViewById(R.id.rl_qqzone);
            if (shareListener != null) {
                rlWechat.setOnClickListener(shareListener);
                rlFriends.setOnClickListener(shareListener);
                rlQQ.setOnClickListener(shareListener);
                rlQQZone.setOnClickListener(shareListener);
            }
        }
    }

    protected void showShare() {
        popShare = View.inflate(this, R.layout.popwindow_share_menu, null);
        View popFull = popShare.findViewById(R.id.ll_pop);
        View tvCancel = popShare.findViewById(R.id.tv_cancel);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindowShared != null) {
                    popupWindowShared.dismiss();
                }
            }
        };
        popFull.setOnClickListener(listener);
        tvCancel.setOnClickListener(listener);
        popupWindowShared = new PopupWindow(popShare, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        if (Build.VERSION.SDK_INT >= 21) popupWindowShared.setClippingEnabled(false);
        popupWindowShared.setTouchable(true);
        popupWindowShared.setOutsideTouchable(true);
        popupWindowShared.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindowShared.setAnimationStyle(R.style.popwindow_anim);
        popupWindowShared.showAtLocation(findViewById(R.id.container), Gravity.BOTTOM, 0, 0);
    }
//    private StatisticsLoader statisticsLoader = new StatisticsLoader(null);

    protected RxPermissions rxPermissions;

    protected ButterKnife.Setter<View, Boolean> VIEWS_VISIAVLE = new ButterKnife.Setter<View, Boolean>() {
        @Override
        public void set(@NonNull View view, Boolean value, int index) {
            final int IS_VISIAVLE = value ? View.VISIBLE : View.GONE;
            view.setVisibility(IS_VISIAVLE);
        }
    };
    protected Toolbar toolbar;
    protected MultipleStatusView msv;

    protected void setBackActivity() {
        View ivBackAct = findViewById(R.id.iv_back);
        if (ivBackAct != null) {
            ivBackAct.setVisibility(View.VISIBLE);
            ivBackAct.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startIconAnim(v);
                    finish();
                }
            });
        }
    }

    protected Toolbar topBar;
    protected FrameLayout viewContent;
    protected View statusbar;
    private View navigator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setLightMode(this);
        rxPermissions = new RxPermissions(this);
        Util.init(this);
        init();
        noTrace = SPUtil.get(this,SPUtil.KEY_NOTRACE,false);
        daoSession = TApp.getDaoSession();
        PushAgent.getInstance(this).onAppStart();
        setContentView(R.layout.activity_topbar_base);
//        topBar = (Toolbar) findViewById(R.id.topBar);
        viewContent = (FrameLayout) findViewById(R.id.contentView);
//        setSupportActionBar(topBar);
//        getSupportActionBar().setDisplayShowTitleEnabled(false);
        statusbar = findViewById(R.id.view_statusbar);
        navigator = findViewById(R.id.nav);
        setToolBarStyle(topBar, statusbar, navigator);
        if (getLayoutID() != 0) {
            getLayoutInflater().inflate(getLayoutID(), viewContent);
            ButterKnife.bind(this);
            presenter = createPresenter();
            progressDialog = new ProgressDialog(this);
            backPage();
            setView();
            setData();
        }
    }

    protected void init() {
    }

    protected void setWhiteStatusBar() {
        StatusBarUtil.setLightMode(this);
        StatusBarUtil.setColor(this, getResources().getColor(android.R.color.white), 0);
    }

    protected void setWhiteStatusBar(int resId) {
        StatusBarUtil.setLightMode(this);
        StatusBarUtil.setColor(this, getResources().getColor(resId), 0);

    }


    protected void setDarkStatusBar(int resId) {
        StatusBarUtil.setColor(this, getResources().getColor(resId));
        StatusBarUtil.setDarkMode(this);
    }

    protected void backPage() {
        View ivBack = findViewById(R.id.iv_back);
        if (ivBack != null) ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startIconAnim(v);
                onBackPressed();
            }
        });
    }

    public void setTopTitle(String title) {
        TextView tvTittle = findViewById(R.id.tv_title);
        if (tvTittle != null) {
            tvTittle.setText(title);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
//        recordInPage();
    }

//    private void recordInPage() {
//        rxPermissions.request(Manifest.permission.READ_PHONE_STATE)
//                .subscribe(grant ->{
//                    if(grant){
//                        TreeMap<String, Object> params = new TreeMap<>();
//                        params.put("uc", Util.getChannelName());
//                        params.put("sn", Util.getSerialNum());
//                        params.put("mn", Util.getDeviceDevice());
//                        params.put("mm", Util.getDeviceModel());
//                        params.put("v", Util.getVersionName());
//                        params.put("ct", 1);
//                        params.put("r", this.getClass().getName());
//                        params.put("vt", 3);
//                        params.put("at", new Date().getTime());
//                        if (statisticsLoader != null)
//                            statisticsLoader.Bas(0, params);
//                    }else{
//
//                    }
//                });
//
//    }

    @Override
    protected void onStop() {
        super.onStop();
//        recordOut();
    }

//    private void recordOut() {
//        if(rxPermissions.isGranted(Manifest.permission.READ_PHONE_STATE)) {
//            TreeMap<String, Object> params = new TreeMap<>();
//            params.put("uc", Util.getChannelName());
//            params.put("sn", Util.getSerialNum());
//            params.put("mn", Util.getDeviceDevice());
//            params.put("mm", Util.getDeviceModel());
//            params.put("v", Util.getVersionName());
//            params.put("ct", 1);
//            params.put("r", getClass().getName());
//            params.put("vt", 0);
//            params.put("at", new Date().getTime());
//            if (statisticsLoader != null)
//                statisticsLoader.Bas(0, params);
//        }
//    }

    @Override
    public void onResume() {
        super.onResume();
        if (BuildConfig.UM) {
            MobclickAgent.onResume(this);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (BuildConfig.UM) {
            MobclickAgent.onPause(this);
        }
    }

    @Override
    protected void onDestroy() {
        if (presenter != null) {
            presenter.onDestroy();
            presenter = null;
        }
        super.onDestroy();
    }


//    protected void setTitleView(String title) {
//        toolbar = findViewById(R.id.toolbar);
//
//        setSupportActionBar(toolbar);
//        getSupportActionBar().setDisplayShowTitleEnabled(false);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//
//        setTitleText(toolbar, title);
//        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
//    }


//    public void setTitle(String title) {
//        ((TextView) findViewById(R.id.txt_title)).setText(title);
//    }
//
//    protected void setTitleText(View rootview, String title) {
//        ((TextView) rootview.findViewById(R.id.txt_title)).setText(title);
//    }

    @Override
    public void showToast(String text) {
        View layout = getLayoutInflater().inflate(R.layout.layout_toast, null);
        ((TextView) layout.findViewById(R.id.toast)).setText(text);
        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();

        //Toast.makeText(this, text, Toast.LENGTH_LONG).show();
    }

    @Override
    public void showProgressDialog(String text) {
        if (progressDialog != null) {
            progressDialog.setMessage(text);
            progressDialog.show();
        }
    }

    @Override
    public void dismissProgressDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    public void startIconAnim(View paramView) {
        ScaleAnimation localScaleAnimation = new ScaleAnimation(0.8F, 1.0F, 0.8F, 1.0F, paramView.getWidth() / 2, paramView.getHeight() / 2);
        localScaleAnimation.setDuration(50L);
        paramView.startAnimation(localScaleAnimation);
    }

    /**
     * 5.0  4.4
     *
     * @param toolbar styleColor
     */
    public void setToolBarStyle(Toolbar toolbar, View topView, View bottomView) {
//        5.0  4.4
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (topView != null) {
                ViewGroup.LayoutParams layoutParams = topView.getLayoutParams();
//                getResources().getDimension(android.R.dimen.status)
                int statusHeight = getStatusHeight();
                Log.i("tuch", "   statusHeight  " + statusHeight);
                //
                layoutParams.height = statusHeight;
//                int mode = SPUtil.get(BaseActivity.this, SPUtil.KEY_NIGHTMODE, 0);
//                if (mode == 0) {
//                    if(Build.VERSION.SDK_INT>=23)
//                    topView.setBackgroundColor(getResources().getColor(R.color.white));
//                    else topView.setBackgroundColor(getResources().getColor(R.color.tab_normal));
//                }else {
//                    topView.setBackgroundColor(getResources().getColor(R.color.windowbackground_night));
//                }
//                topView.setBackgroundResource(R.drawable.shape_gradient);
                topView.setBackgroundColor(getResources().getColor(R.color.white));
//                topView.setLayoutParams(layoutParams);
                topView.setVisibility(View.VISIBLE);
                //第二种
//                toolbar.setPadding(0,toolbar.getPaddingTop()+statusHeight,0,0);
                //下面的导航栏
//                if (haveNavgtion()) {
//                    ViewGroup.LayoutParams layoutParams=bottomView.getLayoutParams();
//                    layoutParams.height+=getNavigationHeight();
//                    Log.i("tuch", "getNavigationHeight  " + getNavigationHeight());
//                    bottomView.setLayoutParams(layoutParams);
////                    bottomView.setBackgroundColor(Color.GREEN);
//                    bottomView.setBackgroundResource(R.mipmap.nav_bg);
//                }
            }

        } else {
            //没救了

        }


    }

    @Override
    public boolean moveTaskToBack(boolean nonRoot) {
        return super.moveTaskToBack(true);
    }


    public int getNavigationHeight() {
        int height = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            String heightStr = clazz.getField("navigation_bar_height").get(object).toString();
            height = Integer.parseInt(heightStr);
            //dp--px
            height = getResources().getDimensionPixelSize(height);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }


        return height;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private boolean haveNavgtion() {
        //屏幕的高度  真实物理的屏幕
        Display display = getWindowManager().getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        display.getRealMetrics(displayMetrics);
        int heightDisplay = displayMetrics.heightPixels;
        //为了防止横屏
        int widthDisplay = displayMetrics.widthPixels;
        DisplayMetrics contentDisplaymetrics = new DisplayMetrics();
        display.getMetrics(contentDisplaymetrics);
        int contentDisplay = contentDisplaymetrics.heightPixels;
        int contentDisplayWidth = contentDisplaymetrics.widthPixels;
        //屏幕内容高度  显示内容的屏幕
        int w = widthDisplay - contentDisplayWidth;
        //哪一方大于0   就有导航栏
        int h = heightDisplay - contentDisplay;
        return w > 0 || h > 0;
    }

    public int getStatusHeight() {
        int height = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            String heightStr = clazz.getField("status_bar_height").get(object).toString();
            height = Integer.parseInt(heightStr);
            //dp--px
            height = getResources().getDimensionPixelSize(height);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }


        return height;
    }


    protected void hideKeyBoard(View view) {
        InputMethodManager ims = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        ims.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }

    protected void showKeyBoard(View view) {
        InputMethodManager ims = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        ims.showSoftInput(view,InputMethodManager.SHOW_FORCED);
    }

    protected boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }

    public boolean isUrl(String str) {
        str = str.toLowerCase();
        String regex = "^((https|http|ftp|rtsp|mms)?://)"//https、http、ftp、rtsp、mms
                + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@  
                + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 例如：199.194.52.184  
                + "|" // 允许IP和DOMAIN（域名）
                + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.  
                + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名  
                + "[a-z]{2,6})" // first level domain- .com or .museum  
                + "(:[0-9]{1,5})?" // 端口号最大为65535,5位数
                + "((/?)|" // a slash isn't required if there is no file name  
                + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        return str.matches(regex);
    }

    public String check(TreeMap<String, Object> params) {
        params.put("appId", Constant.AppId);
        params.put("time", new Date().getTime());
        StringBuilder sign = new StringBuilder();
        for (String s : params.keySet()) {
            sign.append(s + params.get(s));
        }
        sign.append(Constant.AppSecret);
        String sign0 = SHASecrete.getDigestOfString(sign.toString().getBytes()).toUpperCase();
        params.put("sign", sign0);
        return sign0;
    }

}
